package cn.dm.high.chain;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class TradePublisher implements Runnable {

    private Disruptor<Trade> disruptor;
    private CountDownLatch latch;

    private static int PUBLISH_COUNT = 1; // 多次提交

    public TradePublisher(CountDownLatch latch, Disruptor<Trade> disruptor) {
        this.disruptor = disruptor;
        this.latch = latch;
    }

    @Override
    public void run() {
        TradeEventTranslator eventTranslator = new TradeEventTranslator();
        for (int i = 0; i < PUBLISH_COUNT; i++) {
            //新的提交任务的方式
            disruptor.publishEvent(eventTranslator);
        }
        latch.countDown(); // 做完之后,主函数才会向下进行
    }
}


/**
 * Disruptor中提交
 * 法一：RingBuffer提交数据
 * 首先在RingBuffer中获取下一个序号,然后通过序号获取真实的对象,接着再自己设值填充属性,最后发布
 * 参考 cn.dm.quickstart.OrderEventProducer#sendData(java.nio.ByteBuffer)
 * <p>
 * 法二：实现EventTranslator接口,做法更简单,见下面代码
 * 注：translateTo方法相当于法一RingBuffer实现方式的简化版
 */
class TradeEventTranslator implements EventTranslator<Trade> {

    private Random random = new Random();

    @Override
    public void translateTo(Trade event, long sequence) {
        this.generateTrade(event);
    }

    private void generateTrade(Trade event) {
        event.setPrice(random.nextDouble() * 9999);
    }
}
